package com.lzx.iteam.adapter;

import android.app.Dialog;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.lzx.iteam.ContactsTalkDetailActivity;
import com.lzx.iteam.R;
import com.lzx.iteam.emotion.gif.AnimatedGifDrawable;
import com.lzx.iteam.emotion.gif.AnimatedImageSpan;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.DeleteTalkCommentMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.TextViewSpan;
import io.rong.imageloader.core.ImageLoader;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Megan on 15/10/14.
 */
public class DetailCommentListAdapter extends BaseAdapter {

    private Context mContext;
    private ArrayList<Map<String, String>> talkUserDatas;
    private ImageLoader mImageLoader;
    private PreferenceUtil mPreferenceUtil;
    private String userId;
    private AllDialogUtil mDialogUtil;
    public final int DETELE_COMMENT = 1004;
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DETELE_COMMENT:
                    if(msg.arg1==0){
                        Map<String,String> comment=(Map<String,String>)msg.obj;
                        talkUserDatas.remove(comment);
                        notifyDataSetChanged();

                    }
                    break;
            }
        }
    };

    public DetailCommentListAdapter(Context mContext) {
        this.mContext = mContext;
        mImageLoader = ImageLoader.getInstance();
        mPreferenceUtil = PreferenceUtil.getInstance(mContext);
        userId = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");
        mDialogUtil = AllDialogUtil.getInstance((ContactsTalkDetailActivity) mContext);
    }

    public void bindData(ArrayList<Map<String, String>> talkUserDatas) {
        this.talkUserDatas = talkUserDatas;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return talkUserDatas == null ? 0 : talkUserDatas.size();
    }

    @Override
    public Object getItem(int position) {
        return talkUserDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        ViewHolder viewHolder;
        if (talkUserDatas != null && talkUserDatas.size() > 0) {
            final Map<String, String> userData = talkUserDatas.get(position);
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.detail_comment_item, null);
                viewHolder.mImage = (ImageView) convertView.findViewById(R.id.talk_detail_comment_user_img);
                viewHolder.mName = (TextView) convertView.findViewById(R.id.talk_detail_comment_user_name);
                viewHolder.mTime = (TextView) convertView.findViewById(R.id.talk_detail_comment_user_time);
                viewHolder.mContent = (TextView) convertView.findViewById(R.id.talk_detail_comment_content);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.mName.setText(userData.get(Constants.TALK_USER_NAME));
            viewHolder.mTime.setText(DateUtil.getChatTime(Long.parseLong(userData.get(Constants.TALK_CREATE_TIME)) * 1000));
            mImageLoader.displayImage(userData.get(Constants.TALK_USER_IMG), viewHolder.mImage, ImageLoaderInterface.optionHeadImage);
            if (StringUtil.isEmpty(userData.get(Constants.TALK_REPLY_NAME))) {
                SpannableStringBuilder sb = handler(viewHolder.mContent,
                        userData.get(Constants.TALK_COMMENT));
                viewHolder.mContent.setText(sb);
            } else {
                String replyName = userData.get(Constants.TALK_REPLY_NAME);
                SpannableString replyTo = new SpannableString(replyName);//回复人的名字
                TextViewSpan clickableSpan = new TextViewSpan(replyName, mContext, 0,0);
                clickableSpan.setInfo(userData);
                replyTo.setSpan(clickableSpan, 0, replyName.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                viewHolder.mContent.setText("回复");
                viewHolder.mContent.append(replyTo);
                viewHolder.mContent.append(":");
                SpannableStringBuilder sb = handler(viewHolder.mContent,
                        userData.get(Constants.TALK_COMMENT));
                viewHolder.mContent.append(sb);
            }
            viewHolder.mContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (userData.get(Constants.TALK_USER_ID).equals(userId)) {
                        showDeleteTalkCommentDlg(userData);
                    } else {
                        Map<String, String> replyMap = new HashMap<String, String>();
                        replyMap.put(Constants.TALK_REPLY_ID, userData.get(Constants.TALK_USER_ID));
                        replyMap.put(Constants.TALK_REPLY_NAME, userData.get(Constants.TALK_USER_NAME));
                        replyMap.put(Constants.TALK_TYPE, "3");
                        ((ContactsTalkDetailActivity) mContext).showBottomLayout(replyMap);

                    }
                }
            });
        }
        return convertView;
    }

    class ViewHolder {
        ImageView mImage;
        TextView mName;
        TextView mTime;
        TextView mContent;
    }

    private SpannableStringBuilder handler(final TextView gifTextView, String content) {
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            String tempText = m.group();
            try {
                String num = tempText.substring("#[face/png/f_static_".length(), tempText.length() - ".png]#".length());
                String gif = "face/gif/f" + num + ".gif";
                /**
                 * 如果open这里不抛异常说明存在gif，则显示对应的gif
                 * 否则说明gif找不到，则显示png
                 * */
                InputStream is = mContext.getAssets().open(gif);
                sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), m.start(), m.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                is.close();
            } catch (Exception e) {
                String png = tempText.substring("#[".length(), tempText.length() - "]#".length());
                try {
                    int resID = mContext.getResources().getIdentifier(png.split("/")[2].substring(0, png.split("/")[2].indexOf(".")), "drawable", mContext.getApplicationInfo().packageName);
                    sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeResource(mContext.getResources(), resID)), m.start(), m.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                    sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeStream(mContext.getAssets().open(png))), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
//                e.printStackTrace();
            }
        }
        return sb;
    }


    public void showDeleteTalkCommentDlg(final Map<String,String> comment) {

        String okText = mContext.getString(R.string.label_btn_delete);
        String cancelText = mContext.getString(R.string.cancel);
        mDialogUtil.titleDeleteMsgStyle(okText, cancelText, "删除该条评论");
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                deleteTalkComment(comment);
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }

    private void deleteTalkComment(Map<String, String> comment) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TALK_ID, comment.get(Constants.TALK_ID)));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TALK_ABOUT_ID, comment.get(Constants.TALK_ABOUT_ID)));
        DeleteTalkCommentMsg message = new DeleteTalkCommentMsg(mHandler.obtainMessage(DETELE_COMMENT), comment);
        message.mApi = AsynHttpClient.API_TALK_DEL_REPLY;
        message.mParams = nvps;
        AsynHttpClient.getInstance(mContext).execTalkHttp(message);
    }


}
